package kkb.IOTest;

import org.junit.Test;

import java.io.*;

public class XuLieHua {

    // 序列化
    @Test
    public void xuliehua() throws IOException {

        Book book = new Book("西游记","200元");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D://book.txt"));
        objectOutputStream.writeObject(book);
        objectOutputStream.close();


    }


    //反序列化
    @Test
    public void fanxuliehua() throws IOException, ClassNotFoundException {

        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D://book.txt"));
        Object o = objectInputStream.readObject();
        System.out.println(o);
        objectInputStream.close();

    }



}

//想要类被序列化得 实现Serializable 【他就是一个标记，让程序认识他  使他可以被序列化】
// 如果不实现这个接口  程序会报错
class Book implements Externalizable {

    private String name;

    private  String money;




    public Book(String name,String money){
        this.name = name;
        this.money = money;
    }

    public Book(){

    }


    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", money='" + money + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(name);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = (String) in.readObject();
    }
}
